package com.lh_travel.lohas.fragment;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.transition.TransitionInflater;
import android.util.Log;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.activity.CalendarActivity;
import com.lh_travel.lohas.activity.ContentSearchActivity;
import com.lh_travel.lohas.activity.HomeActivity;
import com.lh_travel.lohas.activity.HotelListActivity;
import com.lh_travel.lohas.activity.HotelLoadingActivity;
import com.lh_travel.lohas.base.MainApplication;
import com.lh_travel.lohas.base.UnLazyBasefragment;
import com.lh_travel.lohas.domain.CommentIntentBean;
import com.lh_travel.lohas.domain.Record;
import com.lh_travel.lohas.interfaces.ContentChange;
import com.lh_travel.lohas.interfaces.PermissionListener;
import com.lh_travel.lohas.utils.DateTimeUtil;
import com.lh_travel.lohas.utils.Preferences;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by aaron on 2018/6/2.
 */
@SuppressLint("ValidFragment")
public class HomeSearchFragment extends UnLazyBasefragment {

    private String Tag = "HomeSearchFragment";
    private TextView tv_keyword;
    private TextView tv_checkin_date;
    private TextView tv_checkin_week;
    private TextView tv_checkout_date;
    private TextView tv_checkout_week;
    private ArrayList<String> permission;
    private String checkIn;
    private String checkOut;
    private boolean first = true;
    private ContentChange iChange;
    private LinearLayout ll_checkin, ll_checkout;
    private Button btn_search;
    private String belong;
    private MyThread t;
    private ImageView img_shot;
    private RelativeLayout rl_shot;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 1:

                    tv_keyword.setText((String) msg.obj);
                    belong = mApp.getPreference(Preferences.LOCAL.COUNTRY);
                    break;
            }

        }
    };

    public HomeSearchFragment() {
    }

    public HomeSearchFragment(ContentChange iChange) {
        this.iChange = iChange;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_search;
    }

    @Override
    protected void initView() {

        String shot = mApp.path;

        if (shot != null) {

            setShot(shot);
        } else {

            setShot(null);
        }
    }

    @Override
    protected void initData() {

        //---------------------------关键字----------------------
        //先看有没有搜索记录,没有就用定位记录,定位记录也没有就用提示字"请选择要搜索的内容"
        List<Record> list = mApp.getListPrefernce(Preferences.LOCAL.SEARCH_KEYWORD);
        if (list.size() > 0) {
            // tv_keyword.setText(mApp.getPreference(Preferences.LOCAL.SEARCH_KEYWORD));

            tv_keyword.setText(list.get(0).title);
            belong = list.get(0).belong;

        } else if (mApp.getPreference(Preferences.LOCAL.CITY) != null && mApp.getPreference(Preferences.LOCAL.CITY).length() > 0) {
            tv_keyword.setText(mApp.getPreference(Preferences.LOCAL.CITY));

        } else {

            //检查权限
            checkPermissions();
        }

        //--------------------------入住和离店日期------------------
        //入住日期用今天,离店日期用+1
        Date date_now = DateTimeUtil.gainCurrentDate();
        Date date_tor = DateTimeUtil.addDateTime(date_now, 24);

        //换算成xx月xx日
        String str_now = DateTimeUtil.dateToStrCH(date_now);
        String str_tor = DateTimeUtil.dateToStrCH(date_tor);

        checkIn = DateTimeUtil.anyDateToStr(date_now, "yyyy-MM-dd");
        checkOut = DateTimeUtil.anyDateToStr(date_tor, "yyyy-MM-dd");

        //计算出星期几
        String week_now = DateTimeUtil.dateInWeek(date_now);
        String week_tor = DateTimeUtil.dateInWeek(date_tor);

        tv_checkin_date.setText(str_now);
        tv_checkin_week.setText(week_now);

        tv_checkout_date.setText(str_tor);
        tv_checkout_week.setText(week_tor);

    }

    @Override
    protected void findView() {
        tv_keyword = findViewByID(R.id.tv_keyword);
        tv_checkin_date = findViewByID(R.id.tv_checkin_date);
        tv_checkin_week = findViewByID(R.id.tv_checkin_week);
        tv_checkout_date = findViewByID(R.id.tv_checkout_date);
        tv_checkout_week = findViewByID(R.id.tv_checkout_week);
        btn_search = findViewByID(R.id.btn_search);
        ll_checkin = findViewByID(R.id.ll_checkin);
        ll_checkout = findViewByID(R.id.ll_checkout);
        img_shot = findViewByID(R.id.img_shot);
        rl_shot = findViewByID(R.id.rl_shot);

        tv_keyword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mContext.startActivity(new Intent(mContext, ContentSearchActivity.class));
            }
        });

        ll_checkin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, CalendarActivity.class);
                intent.putExtra("mutil", true);

                intent.putExtra("checkIn", checkIn);
                intent.putExtra("checkOut", checkOut);

                mContext.startActivity(intent);
            }
        });

        ll_checkout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, CalendarActivity.class);
                intent.putExtra("mutil", false);

                intent.putExtra("checkIn", checkIn);
                intent.putExtra("checkOut", checkOut);

                mContext.startActivity(intent);
            }
        });

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //  Intent intent = new Intent(mContext, HotelListActivity.class);

                Intent intent = new Intent(mContext, HotelLoadingActivity.class);

                CommentIntentBean bean = new CommentIntentBean();

                if (tv_keyword.getText().toString().trim().length() == 0){
                    return;
                }

                if (tv_keyword.getText().toString().trim().equals("我的附近")){
                    bean.keyWord = "";

                }else {
                    bean.keyWord = tv_keyword.getText().toString().trim();

                }

                bean.belong = belong;

                bean.checkIn = checkIn;

                bean.checkOut = checkOut;

                t = new MyThread(mApp, tv_keyword.getText().toString().trim(), belong);

                t.start();

                intent.putExtra("detail", bean);

                startActivity(intent);
                getActivity().overridePendingTransition(0, 0);
            }
        });
    }

    /**
     * 检查权限,然后申请定位
     */
    private void checkPermissions() {

        permission = new ArrayList<>();

        permission.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
        permission.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
        permission.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        permission.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
        permission.add(android.Manifest.permission.READ_PHONE_STATE);

        checkMyPermission(permission, new PermissionListener() {
            @Override
            public void onGranted() {

                autoLocation(new AMapLocationListener() {
                    @Override
                    public void onLocationChanged(AMapLocation aMapLocation) {

                        int errorCode = aMapLocation.getErrorCode();
                        /*
                         *//**
                         * 0

                         定位失败

                         请通过AMapLocation.getErrorCode()方法获取错误码，并参考错误码对照表进行问题排查。

                         1

                         GPS定位结果

                         通过设备GPS定位模块返回的定位结果，精度较高，在10米－100米左右

                         2

                         前次定位结果

                         网络定位请求低于1秒、或两次定位之间设备位置变化非常小时返回，设备位移通过传感器感知。

                         4

                         缓存定位结果

                         返回一段时间前设备在同样的位置缓存下来的网络定位结果

                         5

                         Wifi定位结果

                         属于网络定位，定位精度相对基站定位会更好，定位精度较高，在5米－200米之间。

                         6

                         基站定位结果

                         纯粹依赖移动、联通、电信等移动网络定位，定位精度在500米-5000米之间。

                         8

                         离线定位结果
                         *//*
                        int type = aMapLocation.getLocationType();

                        //lat
                        double latitude = aMapLocation.getLatitude();

                        //lng
                        double longitude = aMapLocation.getLongitude();

                        ///获取精度信息
                        float accuracy = aMapLocation.getAccuracy();

                        //地址
                        String address = aMapLocation.getAddress();

                        //国家
                        String country = aMapLocation.getCountry();

                        //省份
                        String province = aMapLocation.getProvince();

                        //市
                        String city = aMapLocation.getCity();

                        //区域
                        String district = aMapLocation.getDistrict();

                        //街道
                        String street = aMapLocation.getStreet();

                        //获取GPS的当前状态
                        int gpsAccuracyStatus = aMapLocation.getGpsAccuracyStatus();*/

                        if (errorCode == 0) {

                            //定位成功
                            double latitude = aMapLocation.getLatitude();
                            double longitude = aMapLocation.getLongitude();
                            String country = aMapLocation.getCountry();
                            String city = aMapLocation.getCity();

                            //把结果保存起来
                            mApp.setPreference(Preferences.LOCAL.LAT, latitude + "");
                            mApp.setPreference(Preferences.LOCAL.LNG, longitude + "");
                            mApp.setPreference(Preferences.LOCAL.CITY, city);

                            if (country.equals("中国")) {
                                mApp.setPreference(Preferences.LOCAL.COUNTRY, "cn");
                            } else {
                                mApp.setPreference(Preferences.LOCAL.COUNTRY, "foreign");
                            }

                            sendHandleMsg(1, city);

                            // showMessage(city);

                        } else {

                            showMessage("定位失败,请检查当前网络状态");

                        }
                    }
                });
            }

            @Override
            public void onDenied(List<Integer> deniedPermission) {

                /**
                 * 定位和权限:
                 * ACCESS_COARSE_LOCATION & ACCESS_FINE_LOCATION : errorcode:12
                 */

                //权限请求失败

                String denPermission = "";

                if (deniedPermission.size() > 0) {

                    denPermission = "定位权限失败,无法定位";

                    showMyDialog("权限请求失败", denPermission, "申请权限", null, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            dialog.dismiss();
                            startActivity(getAppDetailSettingIntent());
                        }
                    });
                }
            }

            @Override
            public void hasPermission() {
                autoLocation(new AMapLocationListener() {
                    @Override
                    public void onLocationChanged(AMapLocation aMapLocation) {

                        int errorCode = aMapLocation.getErrorCode();
                        if (errorCode == 0) {

                            //定位成功
                            double latitude = aMapLocation.getLatitude();
                            double longitude = aMapLocation.getLongitude();
                            String country = aMapLocation.getCountry();
                            String city = aMapLocation.getCity();

                            //把结果保存起来
                            mApp.setPreference(Preferences.LOCAL.LAT, latitude + "");
                            mApp.setPreference(Preferences.LOCAL.LNG, longitude + "");
                            mApp.setPreference(Preferences.LOCAL.CITY, city);

                            if (country.equals("中国")) {
                                mApp.setPreference(Preferences.LOCAL.COUNTRY, "cn");
                            } else {
                                mApp.setPreference(Preferences.LOCAL.COUNTRY, "foreign");
                            }

                            sendHandleMsg(1, city);

                            // showMessage(city);

                        } else {

                            showMessage("定位失败,请检查当前网络状态" + errorCode);

                        }
                    }
                });
            }
        });

    }

    private void sendHandleMsg(int what, Object obj) {
        Message msg = mHandler.obtainMessage();

        msg.what = what;
        msg.obj = obj;

        mHandler.sendMessage(msg);
    }

    public Intent getAppDetailSettingIntent() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", mContext.getPackageName());
        }
        return localIntent;
    }

    public void setKeyword(String keyword, String belong) {
        tv_keyword.setText(keyword);
        this.belong = belong;
    }

    public void setDate(String checkin, String checkout) {

        try {
            tv_checkin_date.setText(DateTimeUtil.strTostr2(checkin).substring(5));
            tv_checkout_date.setText(DateTimeUtil.strTostr2(checkout).substring(5));
        } catch (Exception e) {
            e.printStackTrace();
        }

        tv_checkin_week.setText(DateTimeUtil.GetWeek(checkin, "yyyy-MM-dd"));
        tv_checkout_week.setText(DateTimeUtil.GetWeek(checkout, "yyyy-MM-dd"));

        this.checkIn = checkin;
        this.checkOut = checkout;

    }

    public void setShot(String path) {

        if (path != null) {

            img_shot.setImageBitmap(BitmapFactory.decodeFile(path));
            rl_shot.setVisibility(View.VISIBLE);

            int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            rl_shot.measure(w, h);
            int height = rl_shot.getMeasuredHeight();
            int width = rl_shot.getMeasuredWidth();

            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) img_shot.getLayoutParams();

            params.height = (int) (height * 0.8);
            params.width = (int) (width * 0.8);

            img_shot.setLayoutParams(params);

            ScaleAnimation animation = new ScaleAnimation(1.2f, 1.0f, 1.2f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

            animation.setDuration(300);

            img_shot.startAnimation(animation);

            img_shot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent(mContext, HotelListActivity.class);

                    startActivity(intent);
                    getActivity().overridePendingTransition(0, 0);
                }
            });

        } else if (rl_shot != null) {
            rl_shot.setVisibility(View.GONE);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (t != null)
            t.close();
    }

    private static class MyThread extends Thread {

        private boolean mRunning = false;

        private String keyWord;
        private String belong;
        private MainApplication mApp;

        public MyThread(MainApplication mapp, String keyword, String belong) {
            this.keyWord = keyword;
            this.belong = belong;
            this.mApp = mapp;
        }

        @Override
        public void run() {
            mRunning = true;

            mApp.setListPrefernce(Preferences.LOCAL.SEARCH_KEYWORD, keyWord, belong);

        }

        public void close() {
            mRunning = false;
        }
    }
}
